Variables and Data Types in Dart
Variables and data types are fundamental concepts in Dart programming. They are
used to store, organize, and work with different kinds of information in a
Flutter application. JustAcademy's Flutter curriculum includes Dart programming
fundamentals such as variables, data types, operators, control statements,
functions, collections, and asynchronous programming. :contentReference[oaicite:0]{index=0}
Dart is the programming language used with Flutter to build applications from a
single codebase. Understanding variables and data types is therefore an important
foundation before working with Flutter widgets, APIs, databases, Firebase, and
application state.
Course:
JustAcademy Flutter Training
Course Demo:
Register for Flutter Course Demo
1. What Is a Variable?
A variable is a named storage location used to hold a value. The value stored in
a variable can represent information such as a person's name, age, price, marks,
login status, or a collection of items.
Basic Example
String name = "Rahul";
int age = 25;
In this example:
String is the data type.
name is the variable name.
"Rahul" is the stored value.
int is an integer data type.
age is the variable name.
25 is the stored value.
2. Why Are Variables Important?
Variables allow programs to store and process dynamic information.
String studentName = "Amit";
int marks = 85;
print(studentName);
print(marks);
Variables are commonly used for:
- User information
- Product information
- Prices and quantities
- Application settings
- API response data
- Form input values
- Application state
- Lists of records
3. Declaring a Variable
A variable can be declared by specifying its data type followed by its name.
int age;
String name;
double price;
bool isLoggedIn;
At this point, the variables have been declared but have not been explicitly
assigned values.
4. Initializing a Variable
Assigning a value to a variable is called initialization.
int age = 25;
String name = "Rahul";
double price = 499.99;
bool isLoggedIn = true;
5. Declaration and Initialization Together
In most programs, variables are declared and initialized in the same statement.
String city = "Mumbai";
int students = 100;
double percentage = 87.5;
bool active = true;
6. Explicit Data Types
Dart allows developers to explicitly specify the type of a variable.
int age = 25;
double salary = 45000.50;
String name = "Priya";
bool isEmployee = true;
Explicit types make the intended type of a value clear and help catch many
incorrect assignments during development.
7. The var Keyword
Dart supports the var keyword for type inference. Dart determines
the variable's type from the value assigned to it.
var name = "Rahul";
var age = 25;
var price = 499.50;
var active = true;
Dart can infer these as String, int,
double, and bool respectively.
Example
var city = "Mumbai";
print(city);
Once the inferred type is established, a variable declared with var
does not become a completely unrestricted variable merely because var
was used.
8. The dynamic Type
The dynamic type allows a variable to hold values of different types.
dynamic value = 100;
print(value);
value = "Hello";
print(value);
value = true;
print(value);
dynamic provides flexibility, but it should be used carefully because
it reduces the amount of type checking performed by the compiler.
9. Main Data Types in Dart
Dart provides several important built-in data types.
| Data Type |
Purpose |
Example |
int |
Whole numbers |
int age = 25; |
double |
Decimal numbers |
double price = 99.50; |
num |
Integer or decimal numbers |
num value = 10.5; |
String |
Text |
String name = "Amit"; |
bool |
True/false values |
bool active = true; |
List |
Ordered collection |
List names = []; |
Set |
Unique collection |
Set numbers = {}; |
Map |
Key-value collection |
Map scores = {}; |
Object |
General Dart object type |
Object value = "Hello"; |
10. int Data Type
The int type is used for whole numbers without a fractional part.
int age = 25;
int quantity = 10;
int score = 95;
Example
void main() {
int a = 10;
int b = 20;
int total = a + b;
print(total);
}
Output:
30
11. double Data Type
The double type is used for numbers that can contain decimal values.
double price = 499.99;
double height = 5.8;
double percentage = 87.5;
Example
double productPrice = 799.50;
double discount = 50.25;
double finalPrice = productPrice - discount;
print(finalPrice);
12. num Data Type
The num type can represent both integer and decimal numeric values.
num value = 100;
value = 100.50;
print(value);
Use int when you specifically need whole numbers, double
for decimal values, and num when either numeric form is appropriate.
13. String Data Type
The String type is used to store text.
String firstName = "Rahul";
String city = "Mumbai";
String course = "Flutter Training";
String Concatenation
String firstName = "Rahul";
String lastName = "Sharma";
String fullName = firstName + " " + lastName;
print(fullName);
Output:
Rahul Sharma
String Interpolation
Dart supports string interpolation using the $ symbol.
String name = "Rahul";
int age = 25;
print("My name is $name and I am $age years old.");
For expressions, use ${}:
int a = 10;
int b = 20;
print("Total: ${a + b}");
14. bool Data Type
The bool data type represents a Boolean value. It can contain
either true or false.
bool isLoggedIn = true;
bool isAdmin = false;
bool paymentCompleted = true;
Using bool With Conditions
bool isLoggedIn = true;
if (isLoggedIn) {
print("Welcome to the application");
}
15. List Data Type
A List stores an ordered collection of values. Lists are commonly
used in Flutter applications to represent collections such as products,
users, messages, or menu items.
List fruits = [
"Apple",
"Banana",
"Mango"
];
Accessing List Items
List fruits = [
"Apple",
"Banana",
"Mango"
];
print(fruits[0]);
print(fruits[1]);
Output:
Apple
Banana
Adding an Item
fruits.add("Orange");
Removing an Item
fruits.remove("Banana");
List Length
print(fruits.length);
16. Set Data Type
A Set represents a collection in which each value is unique.
Set cities = {
"Mumbai",
"Delhi",
"Pune"
};
Sets are useful when duplicate values should not be stored.
Set numbers = {1, 2, 3};
numbers.add(4);
numbers.add(2);
print(numbers);
17. Map Data Type
A Map stores data in key-value pairs.
Map marks = {
"Math": 85,
"Science": 90,
"English": 80
};
Accessing a Map Value
print(marks["Math"]);
Output:
85
Adding a Map Entry
marks["Computer"] = 95;
18. Object Data Type
Object can represent values of different Dart types while retaining
a more restrictive type contract than dynamic.
Object value = "Hello";
print(value);
An Object variable can later refer to another kind of object:
Object value = "Hello";
value = 100;
print(value);
19. Null and Nullable Variables
Dart uses null safety. A normal non-nullable variable is expected to contain a
value, while a nullable variable can also contain null.
Nullable Variable
String? name;
name = null;
The ? after the type indicates that the variable can contain
null.
Nullable Integer
int? age;
age = null;
age = 25;
20. final Variables
The final keyword creates a variable whose value can be assigned
only once.
final String name = "Rahul";
final int age = 25;
This is not allowed:
final int age = 25;
// Cannot assign another value to age
// age = 30;
21. const Variables
The const keyword is used for compile-time constants.
const double pi = 3.14159;
const String appName = "My Flutter App";
final vs const
| Feature |
final |
const |
| Assignment |
Assigned once |
Compile-time constant |
| Can be runtime value? |
Yes |
No |
| Can be reassigned? |
No |
No |
22. Type Inference
Dart can automatically determine the type of a variable when its initial value
is known.
var name = "Amit";
var age = 22;
var salary = 35000.50;
var active = true;
Conceptually, Dart infers:
String name = "Amit";
int age = 22;
double salary = 35000.50;
bool active = true;
23. Generic Data Types
Generics allow you to specify what type of values a collection should contain.
Generic List
List names = [
"Amit",
"Rahul",
"Priya"
];
Generic List of Integers
List numbers = [
10,
20,
30
];
Generic Map
Map marks = {
"Math": 90,
"Science": 85
};
24. Changing Variable Values
Variables declared without final or const can generally
be assigned a new value compatible with their declared type.
int age = 20;
age = 21;
print(age);
Output:
21
25. Variables With Operators
Variables can be used in mathematical operations.
int price = 100;
int quantity = 3;
int total = price * quantity;
print(total);
Output:
300
26. Variables With Conditions
int marks = 75;
if (marks >= 40) {
print("Pass");
} else {
print("Fail");
}
27. Variables With Functions
Variables can be passed to functions as arguments.
void greet(String name) {
print("Hello $name");
}
void main() {
String studentName = "Amit";
greet(studentName);
}
28. Variables in Flutter Applications
Variables are used throughout Flutter applications to store information that
widgets and application logic need. For example:
String productName = "Laptop";
double productPrice = 55000.00;
bool isAvailable = true;
int quantity = 2;
These values could represent information displayed on an e-commerce screen.
Flutter-Style Example
String title = "Flutter Course";
String instructor = "Trainer";
double price = 35000;
bool available = true;
29. Example: Student Data
void main() {
String name = "Rahul";
int age = 21;
double percentage = 86.5;
bool passed = true;
print("Name: $name");
print("Age: $age");
print("Percentage: $percentage");
print("Passed: $passed");
}
30. Example: Product Data
void main() {
String productName = "Smartphone";
double price = 24999.99;
int quantity = 2;
bool inStock = true;
double total = price * quantity;
print("Product: $productName");
print("Price: $price");
print("Quantity: $quantity");
print("In Stock: $inStock");
print("Total: $total");
}
31. Example: User Data Using Map
void main() {
Map user = {
"name": "Amit",
"age": 25,
"email": "[email protected]",
"active": true
};
print(user["name"]);
print(user["age"]);
print(user["email"]);
print(user["active"]);
}
In production code, using more specific types or dedicated model classes is
generally preferable to relying heavily on dynamic.
32. Example: List of Products
List products = [
"Laptop",
"Mobile",
"Tablet",
"Headphones"
];
for (String product in products) {
print(product);
}
33. Example: List of Prices
List prices = [
100.50,
250.75,
499.99
];
double total = 0;
for (double price in prices) {
total += price;
}
print("Total: $total");
34. Understanding Static Type Checking
Dart is strongly typed. A variable declared with a specific type is expected
to contain a compatible value.
int age = 25;
The following assignment is invalid:
// Incorrect
// age = "Twenty-five";
The variable is an int, so assigning a String is not
valid.
35. Type Checking With is
Dart provides the is operator to check the runtime type of a value.
Object value = "Hello";
if (value is String) {
print("The value is a String");
}
36. Type Casting
When appropriate, Dart allows values to be treated as a more specific type.
Object value = "Hello";
String text = value as String;
print(text);
Type casts should be used only when the type assumption is valid; otherwise,
a runtime error can occur.
37. Variable Naming Rules
Good variable names make code easier to understand.
Good Examples
String firstName = "Rahul";
int studentAge = 20;
double productPrice = 499.99;
bool isLoggedIn = true;
Avoid Unclear Names
String x = "Rahul";
int a = 20;
double p = 499.99;
Short names can sometimes be appropriate for small local calculations, but
descriptive names are generally easier to maintain.
38. Naming Conventions in Dart
Dart commonly uses lowerCamelCase for variable and method names.
String firstName = "Amit";
int totalMarks = 450;
bool isUserLoggedIn = true;
Class names commonly use UpperCamelCase:
class StudentProfile {
}
39. Local Variables
A variable declared inside a function or block is generally a local variable
and is available within its relevant scope.
void main() {
String name = "Rahul";
print(name);
}
40. Variable Scope
Scope determines where a variable can be accessed.
void main() {
int age = 25;
if (age > 18) {
String message = "Adult";
print(message);
}
// message is not available here
}
41. Data Type Selection Guide
| Requirement |
Recommended Type |
Example |
| Whole number |
int |
int age = 25; |
| Decimal number |
double |
double price = 99.99; |
| Number that can be int or double |
num |
num value = 10.5; |
| Text |
String |
String name = "Amit"; |
| True/false |
bool |
bool active = true; |
| Ordered values |
List |
List names = []; |
| Unique values |
Set |
Set ids = {}; |
| Key-value data |
Map |
Map scores = {}; |
| Nullable value |
Type? |
String? name; |
42. Common Mistakes
Mistake 1: Assigning the Wrong Type
int age = 25;
// Incorrect:
// age = "Twenty five";
Mistake 2: Using dynamic Unnecessarily
dynamic name = "Rahul";
If the value is known to always be a string, using String is usually
clearer:
String name = "Rahul";
Mistake 3: Forgetting Nullability
String? username;
username = null;
Use a nullable type when a value is legitimately allowed to be absent.
Mistake 4: Reassigning final
final int age = 25;
// Not allowed:
// age = 30;
43. Best Practices
- Choose meaningful variable names.
- Use explicit types when they improve clarity.
- Use
var when type inference keeps the code clear.
- Avoid unnecessary use of
dynamic.
- Use
final when a variable should be assigned only once.
- Use
const for compile-time constants.
- Use nullable types deliberately when
null is a valid state.
- Use generic collections such as
List and
Map when the collection type is known.
- Keep variable scope as small as practical.
- Use Dart's formatting tools to keep code consistent.
44. Variables and Data Types in Flutter
Variables and data types become especially important when developing real Flutter
applications. JustAcademy's Flutter curriculum connects Dart fundamentals with
later topics such as widgets, API integration, local storage, Firebase, state
management, testing, and deployment. :contentReference[oaicite:1]{index=1}
For example, an application might maintain:
String userName = "Rahul";
int cartItems = 3;
double cartTotal = 1499.99;
bool isLoggedIn = true;
List categories = [
"Electronics",
"Clothing",
"Books"
];
These values could be used by Flutter widgets to display information and update
the application's interface.
45. Complete Example
void main() {
// User information
String name = "Amit";
int age = 24;
double accountBalance = 12500.75;
bool active = true;
// Product list
List products = [
"Laptop",
"Mobile",
"Tablet"
];
// User scores
Map scores = {
"Math": 90,
"Science": 85,
"English": 88
};
print("Name: $name");
print("Age: $age");
print("Balance: $accountBalance");
print("Active: $active");
print("Products: $products");
print("Math Score: ${scores["Math"]}");
}
46. Quick Revision
- A variable stores a value under a name.
- Dart supports explicit types such as
int, double,
String, and bool.
var enables type inference.
dynamic allows a variable to hold values of different types.
int represents whole numbers.
double represents decimal numbers.
num can represent integer or decimal numbers.
String stores text.
bool stores true or false.
List stores ordered collections.
Set stores unique values.
Map stores key-value pairs.
final allows one assignment.
const represents compile-time constants.
Type? creates a nullable type.
- Generics make collections more type-safe.
47. Practice Exercises
- Create variables for your name, age, city, and country.
- Create a program to calculate the total price of three products.
- Create a Boolean variable representing whether a user is logged in.
- Create a list containing five programming languages.
- Create a set containing five unique numbers.
- Create a map containing student names and marks.
- Create a nullable
String variable.
- Create a
final variable for a user's date of birth.
- Create a
const variable for the value of PI.
- Create a small Flutter-style product data model using multiple Dart data types.
48. Key Takeaways
Variables and data types form the foundation of Dart programming. A good
understanding of these concepts makes it easier to work with conditions, loops,
functions, collections, classes, API data, databases, and Flutter application
state.
JustAcademy's Flutter curriculum places variables, data types, operators,
functions, collections, and other Dart fundamentals early in the learning path
before progressing into Flutter UI and application development. :contentReference[oaicite:2]{index=2}
49. Learn Flutter with JustAcademy
Explore the complete Flutter training program:
JustAcademy Flutter Training
To register for a Flutter course demo:
Register for Flutter Course Demo